﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using CLibArtreve.bll;
using CLibArtreve.models;
using Krystalware.SlickUpload;
using Krystalware.SlickUpload.Web.Controls;
using CLibArtreve.security;

namespace WebAppArtreve.views.shared.components.arts
{
    public partial class WUCAddArt : System.Web.UI.UserControl
    {
        //VARIABLES
        private Int64 _artId = 0;        
        private int _numberOfUploadedFiles;
        private string _connectionString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings["ARTREVEConnectionString"].ConnectionString;
            }
        }

        private Int64? _userId
        {
            get
            {
                ArtreveIdentity identity = (ArtreveIdentity)Context.User.Identity;
                return identity.User.Id;
            }
        }

        public IList<ArtPicture> UploadedImages
        {
            get
            {
                if(this.ViewState["UploadedImages"] == null)
                    this.ViewState["UploadedImages"] = new List<ArtPicture>();

                return this.ViewState["UploadedImages"] as List<ArtPicture>;
            }
            set
            {
                this.ViewState["UploadedImages"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Id"] != null && IsPostBack != true)
            {
                try
                {
                    //1. BLL
                    //-----------------------
                    ArtBLL bllArt = new ArtBLL(_connectionString);
                    ArtPictureBLL bllArtPicture = new ArtPictureBLL(_connectionString);
                    ArtCategoryBLL bllArtCategory = new ArtCategoryBLL(_connectionString);

                    //2. MODELS
                    //----------------------- 
                    Art art = new Art();
                    ArtPicture artPicture = new ArtPicture();   
                    ArtCategory artCategory = new ArtCategory();

                    _artId = Convert.ToInt64(Request.QueryString["Id"]);

                    art = bllArt.GetArtById(_artId);
                    //artPicture = bllArtPicture.GetArtPictureByArtId(_artId);
                    artCategory = bllArtCategory.GetCategoryByArtId(_artId);
                                        
                    this.txtArtName.Text = art.Name;
                    this.txtArtDescription.Text = art.Description;
                    this.txtArtSize.Text = art.Size;
                    this.txtArtPrice.Text = Convert.ToString(art.Price);
                    this.txtArtNumberOf.Text = Convert.ToString(art.Numberof);                    
                    //art.ModifiedDate = Convert.ToDateTime(this.txtArtModificationdate.Text.Trim());                                  art.Spotlighted = false;                    

                    this.ddlCategory.SelectedIndex = Convert.ToInt16(artCategory.ArtId - 1);                    
                }
                catch (Exception ex)
                {
                    throw (ex);
                }
            }
        }
        
        //BUTTON (ADD ART) CLICKED
        protected void linkAddArt_Click(object sender, EventArgs e)
        {
            if (this.Page.IsValid)
            {
                if (Request.QueryString["Id"] != null)
                {
                    UpdateArt();
                }
                else
                {
                    AddNewArt();
                }
            }            
        }

        //ADD ART
        private void AddNewArt()
        {
                //1. BLL
                //-----------------------
                ArtBLL bllArt = new ArtBLL(_connectionString);
                ArtPictureBLL bllArtPicture = new ArtPictureBLL(_connectionString);
                ArtCategoryBLL bllArtCategory = new ArtCategoryBLL(_connectionString);
                UserBLL bllUser = new UserBLL(_connectionString);

                //2. MODELS
                //-----------------------
                Art art = new Art();
                User userBuy = new User();
                ArtPicture artPicture1 = new ArtPicture();
                ArtPicture artPicture2 = new ArtPicture();
                ArtPicture artPicture3 = new ArtPicture();
                ArtCategory artCategory = new ArtCategory();
                try
                {
                    userBuy = bllUser.GetUserById(_userId);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                //3. INSERT ART IN MODEL
                //-----------------------
                try
                {
                    string Price = this.txtArtPrice.Text.Trim();
                    string Count = this.txtArtNumberOf.Text.Trim();

                    art.Name = this.txtArtName.Text.Trim();
                    art.Description = this.txtArtDescription.Text.Trim();
                    art.Size = this.txtArtSize.Text.Trim();
                    art.Price = Price.Length > 0 ? Convert.ToInt64(Price) : 0;
                    art.Numberof = Count.Length > 0 ? Convert.ToInt64(Count) : 0;
                    art.CreationDate = DateTime.Now;
                    art.UserId = userBuy.Id;
                    //art.ModifiedDate = Convert.ToDateTime(this.txtArtModificationdate.Text.Trim());
                    //art.Spotlighted = Convert.ToBoolean(this.txtArtSpotlighted.Text.Trim());
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                try
                {
                    Boolean isSpotlighted = this.cbxSpotlight.Text == "Yes" ? true : false;
                    if (isSpotlighted == true && (userBuy.Tokens - 50) >= 0)
                    {
                        art.Spotlighted = isSpotlighted;
                        //update tokens
                        userBuy.Tokens -= 50;
                        //3. UPDATE USER TOKENS IN DB
                        //----------------------- 
                        bllUser.UpdateUser(userBuy);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                //4. INSERT ART IN DB
                //-----------------------
                try
                {
                    _artId = bllArt.InsertArt(art);
                }
                catch (Exception ex)
                {
                    throw ex;
                }


                //5. INSERT ARTPICTURE IN DB
                //-----------------------
                try
                {
                    foreach (ArtPicture uploadedImage in UploadedImages)
                    {
                        uploadedImage.ArtId = _artId;
                        bllArtPicture.InsertArtPicture(uploadedImage);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                //6. INSERT ARTCATEGORIES IN DB
                //-----------------------
                artCategory.ArtId = _artId;

                try
                {
                    //SELECTED VALUE MOET NOG HET ID ZIJN NIET WOORD
                    artCategory.Id = Convert.ToInt64(this.ddlCategory.SelectedIndex + 1);
                    //bllArtCategory.
                    bllArtCategory.InsertArtCategory(artCategory);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
        }

        //UPDATE ART
        private void UpdateArt()
        {
            try
            {
                //1. BLL
                //-----------------------
                ArtBLL bllArt = new ArtBLL(_connectionString);
                ArtPictureBLL bllArtPicture = new ArtPictureBLL(_connectionString);
                ArtCategoryBLL bllArtCategory = new ArtCategoryBLL(_connectionString);
                UserBLL bllUser = new UserBLL(_connectionString);

                //2. MODELS
                //----------------------- 
                Art art = new Art();
                ArtPicture artPicture1 = new ArtPicture();
                ArtPicture artPicture2 = new ArtPicture();
                ArtPicture artPicture3 = new ArtPicture();
                ArtCategory artCategory = new ArtCategory();
                User userBuy = new User();
                userBuy = bllUser.GetUserById(_userId);

                _artId = Convert.ToInt64(Request.QueryString["Id"]);

                //3. INSERT ART IN MODEL
                //-----------------------                

                art.Id = _artId;
                art.Name = this.txtArtName.Text.ToString().Trim();
                art.Description = this.txtArtDescription.Text.ToString().Trim();
                art.Size = this.txtArtSize.Text.ToString().Trim();
                art.Price = Convert.ToInt64(this.txtArtPrice.Text.ToString().Trim());
                art.Numberof = Convert.ToInt64(this.txtArtNumberOf.Text.ToString().Trim());
                art.CreationDate = DateTime.Now;
                art.UserId = userBuy.Id;
                //art.ModifiedDate = Convert.ToDateTime(this.txtArtModificationdate.Text.Trim());                        

                Boolean isSpotlighted = this.cbxSpotlight.Text == "Yes" ? true : false;

                if (isSpotlighted == true && (userBuy.Tokens - 50) >= 0)
                {
                    art.Spotlighted = Convert.ToBoolean(isSpotlighted);
                    //update tokens
                    userBuy.Tokens -= 50;
                    //3. UPDATE USER TOKENS IN DB
                    //----------------------- 
                    bllUser.UpdateUser(userBuy);
                }

                //4. UPDATE ART IN DB
                //----------------------- 
                bllArt.UpdateArt(art);

                //5. INSERT ARTPICTURE IN DB
                //-----------------------                                                  

                //REMOVE ALL PICTURES
                bllArtPicture.DeleteArtPicture(_artId);

                foreach (ArtPicture uploadedImage in UploadedImages)
                {
                    uploadedImage.ArtId = _artId;
                    bllArtPicture.InsertArtPicture(uploadedImage);
                }

                //6. UPDATE ARTCATEGORIES IN DB
                //----------------------- 
                artCategory.ArtId = _artId;
                artCategory.Id = Convert.ToInt64(this.ddlCategory.SelectedIndex + 1);
                bllArtCategory.UpdateArtCategory(artCategory);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        // GET TIMESTAMP
        private string getTimeStamp()
        {
            var nowDate = DateTime.Now;
            return nowDate.ToString("yyyyMddHHmmssffff");
        }
        
        protected void slickUpload_UploadComplete(object sender, UploadSessionEventArgs e)
        {
            if (e.UploadSession != null && e.UploadSession.State == UploadState.Complete)
            {
                //SHOW UPLOADED FILES
                if (e.UploadSession.UploadedFiles.Count > 0)
                {
                    resultsRepeater.DataSource = e.UploadSession.UploadedFiles;
                    resultsRepeater.DataBind();
                }

                foreach (UploadedFile image in e.UploadedFiles)
                {
                    ArtPicture uploadedImage = new ArtPicture();
                    uploadedImage.Image = getFilenameFromPath(image.ServerLocation);
                    UploadedImages.Add(uploadedImage);
                }

                //HOW MANY FILES?
                _numberOfUploadedFiles = e.UploadSession.UploadedFiles.Count;

                //WHICH FILES WERE UPLOADED?
                this.ArtImage1.ImageUrl = ConfigurationManager.AppSettings["DMSPATH"] + e.UploadSession.UploadedFiles.ElementAt(0).ClientName;
                this.ArtImage1.DescriptionUrl = e.UploadSession.UploadedFiles.ElementAt(0).ClientName;

                if (_numberOfUploadedFiles > 1)
                {
                    this.ArtImage2.ImageUrl = ConfigurationManager.AppSettings["DMSPATH"] + e.UploadSession.UploadedFiles.ElementAt(1).ClientName;
                    this.ArtImage2.DescriptionUrl = e.UploadSession.UploadedFiles.ElementAt(1).ClientName;
                }
                else
                    this.ArtImage2.ImageUrl = "";
                if (_numberOfUploadedFiles > 2)
                {
                    this.ArtImage3.ImageUrl = ConfigurationManager.AppSettings["DMSPATH"] + e.UploadSession.UploadedFiles.ElementAt(2).ClientName;
                    this.ArtImage3.DescriptionUrl = e.UploadSession.UploadedFiles.ElementAt(2).ClientName;
                }
                else
                    this.ArtImage3.ImageUrl = " ";                

                //SET UPLOADED ONES VISIBLE
                this.ArtImage1.Visible = true;
                this.ArtImage2.Visible = true;
                this.ArtImage3.Visible = true;

                //HIDE DATABASE ONES
                this.WUCArtImages.Visible = false;                
            }
            else 
            {
                //ALS HET NIET ZOU LUKKEN ERROR
                uploadResultPanel.Visible = true;
                uploadPanel.Visible = false;
            }
        }

        protected void newUploadButton_Click(object sender, EventArgs e)
        {
            uploadResultPanel.Visible = false;
            uploadPanel.Visible = true;
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            //SET VALIDATION, MAXFILES AND FILESIZE
            int maxFiles = 3;
            int maxFileSize = 1048576;
            string validextensions = "png,jpg,gif,jpeg";

            fileSelector.MaxFiles = maxFiles;
            fileSelector.MaxFileSize = maxFileSize;
            fileSelector.ValidExtensions = validextensions;
        }

        protected string[] splitPath(string path)
        {
            string[] result = path.Split('\\');
            return result;
        }

        protected string getFilenameFromPath(string path)
        {
            string[] chunks = splitPath(path);
            return chunks.Last();
        }

        protected void ODSCategoriesALL_OnObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            //STEP 2. CREATE BLL
            CategoryBLL bllCategories = new CategoryBLL(_connectionString);
            //STEP 3. CONNECT TYPENAME
            e.ObjectInstance = bllCategories;
        }
    }
}